package com.atguigu.system.service.impl;

import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.model.vo.AssignRoleVo;
import com.atguigu.model.vo.SysRoleQueryVo;
import com.atguigu.system.mapper.SysRoleMapper;
import com.atguigu.system.mapper.SysUserRoleMapper;
import com.atguigu.system.service.SysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public Map<String, Object> getRolesByUserId(Long userId) {
        Map<String, Object> resultMap = new HashMap<String,Object>();
        //List<SysRole> allRoles = sysRoleMapper.selectList(null);
        List<SysRole> allRoles = this.list();

        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<SysUserRole> sysUserRoleList =  sysUserRoleMapper.selectList(queryWrapper);
        List<Long> userRoleIds = new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoleList) {
            userRoleIds.add(sysUserRole.getRoleId());
        }
        //Map中的key与前端代码一一对应
        resultMap.put("allRoles",allRoles); //所有角色集合
        resultMap.put("userRoleIds",userRoleIds); //当前用户已经拥有的角色id集合
        return resultMap;
    }

    @Override
    public void doAssign(AssignRoleVo assignRoleVo) {
        Long userId = assignRoleVo.getUserId();
        List<Long> roleIdList = assignRoleVo.getRoleIdList();
        //根据用户id删除原来分配的角色
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        sysUserRoleMapper.delete(queryWrapper);
        //获取所有的角色id

        if (!CollectionUtils.isEmpty(roleIdList)){
            for (Long roleId : roleIdList) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                sysUserRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    public IPage<SysRole> findPage(IPage<SysRole> pageParam, SysRoleQueryVo queryVo) {
        IPage<SysRole> pageResult = sysRoleMapper.findPage(pageParam, queryVo);
        return pageResult;
    }
}
